package com.example.demo.controller;

import com.example.demo.service.FileService;
import com.fasterxml.jackson.databind.JsonNode;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.core.io.ByteArrayResource;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

import com.example.demo.dto.ApiResponse;
@RestController
@RequestMapping("/api/files")
public class FileController {

    private static final String BASE_URL = "http://8.154.32.215/fileuploads";
    private static final String FLASK_UPLOAD_URL_VIDEO = "http://localhost:9121/inference";
    private static final String FLASK_UPLOAD_URL_IMAGE = "http://localhost:9121/video_synthesize";

    @Autowired
    private FileService fileService;

    @PostMapping("/upload")
    public ApiResponse<String> uploadFiles(
            @RequestParam(value = "video", required = false) MultipartFile videoFile,
            @RequestParam(value = "audio", required = false) MultipartFile audioFile,
            @RequestParam(value = "image", required = false) MultipartFile imageFile,
            @RequestParam(value = "file", required = false) MultipartFile file,
            @RequestParam(value = "useFlask", defaultValue = "false") boolean useFlask) throws IOException {

        try {
            // 处理普通文件
            if (file != null) {
                String fileName = fileService.uploadFile(file);
                String fileurl = BASE_URL + "/" + fileName;
                System.out.println("文件网址" + fileurl);
                return ApiResponse.success(fileurl, "普通文件已上传到本地服务器");
            }

            // 处理视频和音频文件
            if (useFlask && ((videoFile == null && imageFile == null) || audioFile == null)) {
                return ApiResponse.error("需要同时上传视频（或图片）和音频文件才能调用 Flask 服务");
            }

            // 保存视频和音频文件到本地
            String videoFileName = videoFile != null ? fileService.uploadFile(videoFile) : null;
            String audioFileName = audioFile != null ? fileService.uploadFile(audioFile) : null;

            // 如果不需要调用 Flask 服务，只保存到本地
            if (!useFlask) {
                String message = "文件已上传到本地服务器"
                        + (videoFileName != null ? ": " + videoFileName : "")
                        + (audioFileName != null ? ", " + audioFileName : "");
                return ApiResponse.success(null, message);
            }

            // 调用 Flask 服务
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);

            org.springframework.util.MultiValueMap<String, Object> body = new org.springframework.util.LinkedMultiValueMap<>();
            if (videoFile != null) {
                body.add("video", new ByteArrayResource(videoFile.getBytes()) {
                    @Override
                    public String getFilename() {
                        return videoFile.getOriginalFilename();
                    }
                });
            }
            if (audioFile != null) {
                body.add("audio", new ByteArrayResource(audioFile.getBytes()) {
                    @Override
                    public String getFilename() {
                        return audioFile.getOriginalFilename();
                    }
                });
            }
            if (imageFile != null) {
                body.add("image", new ByteArrayResource(imageFile.getBytes()) {
                    @Override
                    public String getFilename() {
                        return imageFile.getOriginalFilename();
                    }
                });
            }

            HttpEntity<org.springframework.util.MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
            String flaskUploadUrl = videoFile != null ? FLASK_UPLOAD_URL_VIDEO : FLASK_UPLOAD_URL_IMAGE;

            ResponseEntity<String> response = restTemplate.postForEntity(flaskUploadUrl, requestEntity, String.class);

            if (response.getStatusCode() == HttpStatus.OK) {
                String jsonResponse = response.getBody();
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode jsonNode = objectMapper.readTree(jsonResponse);

                String videoUrl = jsonNode.path("videoUrl").asText();
                return ApiResponse.success(videoUrl, "文件已上传并通过 Flask 服务处理");
            } else {
                return ApiResponse.error("Flask 文件处理失败: " + response.getStatusCode());
            }
        } catch (Exception e) {
            return ApiResponse.error("文件处理失败：" + e.getMessage());
        }
    }

    @GetMapping("/download/{fileName}")
    public ApiResponse<byte[]> getFile(@PathVariable String fileName) {
        try {
            byte[] fileData = fileService.getFile(fileName);
            if (fileData == null) {
                return ApiResponse.error("文件不存在");
            }
            return ApiResponse.success(fileData, "文件下载成功");
        } catch (Exception e) {
            return ApiResponse.error("文件下载失败：" + e.getMessage());
        }
    }
}
